package com.ruoyi.project.lesson.lesson.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.lesson.block.domain.LessonBlock;
import com.ruoyi.project.lesson.block.service.ILessonBlockService;
import com.ruoyi.project.lesson.lesson.domain.Lesson;
import com.ruoyi.project.lesson.lesson.domain.ProvideMethod;
import com.ruoyi.project.lesson.lesson.service.ILessonService;
import com.ruoyi.project.lesson.tag.domain.LessonTag;
import com.ruoyi.project.lesson.tag.service.ILessonTagService;
import com.ruoyi.project.system.dict.domain.DictData;
import com.ruoyi.project.system.dict.service.IDictDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 课程Controller
 *
 * @author shixiangwen
 * @date 2020-12-07
 */
@Controller
@RequestMapping("/lesson/lesson")
public class LessonController extends BaseController {

    private String prefix = "lesson/lesson";

    @Autowired
    private ILessonService lessonService;

    @Autowired
    private ILessonBlockService lessonBlockService;

    @Autowired
    private ILessonTagService lessonTagService;

    @Autowired
    private IDictDataService dictDataService;
    private ProvideMethod provideMethod;


    @RequiresPermissions("lesson:lesson:view")
    @GetMapping()
    public String lesson() {
        return prefix + "/lesson";
    }

    /**
     * 查询课程列表
     */
    @RequiresPermissions("lesson:lesson:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Lesson lesson) {
        startPage();
        List<Lesson> list = lessonService.selectLessonList(lesson);
        return getDataTable(list);
    }

    /**
     * 导出课程列表
     */
    @RequiresPermissions("lesson:lesson:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Lesson lesson) {
        List<Lesson> list = lessonService.selectLessonList(lesson);
        ExcelUtil<Lesson> util = new ExcelUtil<Lesson>(Lesson.class);
        return util.exportExcel(list, "lesson");
    }

    /**
     * 新增课程
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.addAttribute("blocks", lessonBlockService.selectLessonBlockList(new LessonBlock()));
        mmap.addAttribute("tags", lessonTagService.selectAllTags());

        List<DictData> dicts = dictDataService.selectDictDataByType("lesson_provide_method");
        List<ProvideMethod> provideMethods = new ArrayList<>();
        for (DictData dictData : dicts) {
            ProvideMethod provideMethod = new ProvideMethod();
            provideMethod.setId(Integer.parseInt(dictData.getDictValue()));
            provideMethod.setName(dictData.getDictLabel());
            provideMethods.add(provideMethod);
        }
        mmap.addAttribute("provideMethods", provideMethods);


        return prefix + "/add";
    }

    /**
     * 新增保存课程
     */
    @RequiresPermissions("lesson:lesson:add")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Lesson lesson) {

        lesson.setTags(JsonUtil.toJson(lesson.getTagIds()));
        lesson.setBlocks(JsonUtil.toJson(lesson.getBlockIds()));

        lesson.setCreatedTime(DateUtils.getNowDate());

        return toAjax(lessonService.insertLesson(lesson));
    }

    /**
     * 修改课程
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Lesson lesson = lessonService.selectLessonById(id);
        mmap.put("lesson", lesson);

        List<Long> blockIds = JsonUtil.toListObject(lesson.getBlocks(), Long.class);
        List<LessonBlock> blocks = lessonBlockService.selectLessonBlockList(new LessonBlock());
        for (LessonBlock block : blocks) {
            if (blockIds != null && blockIds.contains(block.getId())) {
                block.setFlag(true);
            }
        }

        List<Long> tagIds = JsonUtil.toListObject(lesson.getTags(), Long.class);
        List<LessonTag> tags = lessonTagService.selectAllTags();
        for (LessonTag tag : tags) {
            for (LessonTag subTag : tag.getChildrens()) {
                if (tagIds != null && tagIds.contains(subTag.getId())) {
                    subTag.setFlag(true);
                }
            }
        }

        mmap.addAttribute("blocks", blocks);
        mmap.addAttribute("tags", tags);

        List<Integer> provideMethodIds = null;
        try {
            provideMethodIds = JsonUtil.toListObject(lesson.getProvideMethods(), Integer.class);
        } catch (Exception e) {

        }

        if (provideMethodIds == null) {
            provideMethodIds = new ArrayList<>();
        }

        List<DictData> dicts = dictDataService.selectDictDataByType("lesson_provide_method");
        List<ProvideMethod> provideMethods = new ArrayList<>();
        for (DictData dictData : dicts) {
            ProvideMethod provideMethod = new ProvideMethod();
            Integer provideMethodId = Integer.parseInt(dictData.getDictValue());
            provideMethod.setId(provideMethodId);
            provideMethod.setName(dictData.getDictLabel());
            if (provideMethodIds.contains(provideMethodId)) {
                provideMethod.setFlag(true);
            }
            provideMethods.add(provideMethod);
        }
        mmap.addAttribute("provideMethods", provideMethods);

        return prefix + "/edit";
    }

    /**
     * 修改保存课程
     */
    @RequiresPermissions("lesson:lesson:edit")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Lesson lesson) {

        lesson.setTags(JsonUtil.toJson(lesson.getTagIds()));
        lesson.setBlocks(JsonUtil.toJson(lesson.getBlockIds()));

        return toAjax(lessonService.updateLesson(lesson));
    }

    @RequiresPermissions("lesson:lesson:edit")
    @Log(title = "课程", businessType = BusinessType.GRANT)
    @PostMapping("/updateStatus/{id}")
    @ResponseBody
    public AjaxResult updateStatus(@PathVariable("id") Long id, Long status) {

        Lesson lesson = lessonService.selectLessonById(id);
        lesson.setStatus(status);

        return toAjax(lessonService.updateLesson(lesson));
    }

    /**
     * 删除课程
     */
    @RequiresPermissions("lesson:lesson:remove")
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(lessonService.deleteLessonByIds(ids));
    }
}
